package com.test.nnooolwdeaer.dec_wooden

import android.content.Context
import com.google.gson.Gson
import com.test.nnooolwdeaer.dec_wooden.data_wooden.AppInfo_wooden
import com.test.nnooolwdeaer.dec_wooden.data_wooden.BatteryInfo_wooden
import com.test.nnooolwdeaer.dec_wooden.data_wooden.DeviceInfo_wooden
import com.test.nnooolwdeaer.dec_wooden.data_wooden.HardwareInfo_wooden
import com.test.nnooolwdeaer.dec_wooden.data_wooden.MsgInfo_wooden
import com.test.nnooolwdeaer.dec_wooden.data_wooden.StorageInfo_wooden
import com.test.nnooolwdeaer.dec_wooden.data_wooden.WifiInfo_wooden

class DeviceUtil_wooden(val context: Context, val product: String, val token: String) {

    private fun fetchCommon(path: String, fetchData: () -> String?): String? {
        if (!checkParams(path)) return null
        return fetchData()
    }

    private fun fetchCommonWithParams(
        path: String,
        key: String,
        fetchData: () -> String?
    ): String? {
        if (!checkParams(path)) return null
        val data = fetchData() ?: return null
        val params = commonParams(path).apply { put(key, data) }
        return Gson().toJson(params).trim()

        // TODO: 加密操作
        // ASAesUtil.encryptDefault(result)
    }

    private fun checkParams(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun commonParams(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun fetchDevice(path: String) = fetchCommon(path) {
        DeviceInfo_wooden(context, product, token, path).fetch()
    }

    fun fetchMsg(path: String) = fetchCommon(path) {
        MsgInfo_wooden(context, product, token, path).fetch()
    }

    fun fetchHardware(path: String) = fetchCommonWithParams(path, "deviceHardwareGzip") {
        HardwareInfo_wooden(context).fetch()
    }

    fun fetchBattery(path: String, onResult: (String?) -> Unit) {
        BatteryInfo_wooden(context = context, onResult = { bd ->
            val result = fetchCommonWithParams(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun fetchRam(path: String) = fetchCommonWithParams(path, "deviceStorageGzip") {
        StorageInfo_wooden(context).fetch()
    }

    fun fetchWifi(path: String) = fetchCommonWithParams(path,  "deviceWifiGzip") {
        WifiInfo_wooden(context).fetch()
    }

    fun fetchApp(path: String) = fetchCommonWithParams(path, "appListGzip") {
        AppInfo_wooden(context).fetch()
    }
}